package com.example.rwq_test.ThreadPool.hook;

import java.util.concurrent.*;

/**
 * ShutdownHook处线程池关闭后任务队列里的消息
 *
 * @author renweiqiang
 * @version 1.0.0
 * @createTime 2024/4/8
 */
public class ShutdownHook {
    private static BlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<>();

    static class MyTask implements Runnable {
        private int value;

        public MyTask(int value) {
            this.value = value;
        }

        @Override
        public void run() {
            System.out.println("Task " + value + " is running...");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("Task " + value + " is finish");
        }
    }

    public static void main(String[] args) {
        ExecutorService executorService = new ThreadPoolExecutor(5, 10, 10000, TimeUnit.MILLISECONDS, blockingQueue);

        // 模拟向线程池队列中添加任务
        for (int i = 0; i < 20; i++) {
            executorService.submit(new MyTask(i));
        }

        // 注册ShutdownHook
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {

            System.out.println("Shutting down gracefully..." + blockingQueue.size());
            // 在这里添加消费线程池队列中的消息的逻辑
            // 可以将未处理的任务持久化到数据库或消息队列中
            while (!blockingQueue.isEmpty()) {
                try {
                    Runnable take = blockingQueue.take();
                    take.run();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("Shutting down gracefully finish." + blockingQueue.size());
        }));
        // 关闭服务: 执行以前提交的,但拒绝接受新提交的,有新提交的会抛异常
        executorService.shutdown();
    }

//    public static void main(String[] args) {
//        ExecutorService executorService = new ThreadPoolExecutor(5, 10, 10000, TimeUnit.MILLISECONDS, blockingQueue);
//
//        // 模拟向线程池队列中添加任务
//        for (int i = 0; i < 1000; i++) {
//            executorService.submit(new MyTask(i));
//        }
//
//        // 注册ShutdownHook
//        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
//            List<Runnable> runnables = executorService.shutdownNow();
//            System.out.println("Shutting down gracefully..." + blockingQueue.size());
//            // 在这里添加消费线程池队列中的消息的逻辑
//            // 可以将未处理的任务持久化到数据库或消息队列中
//            for (Runnable runnable : runnables) {
//                runnable.run();
//            }
//        }));
//        try {
//            TimeUnit.SECONDS.sleep(1000);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
//    }
}
